
// Definition for singly-linked list.
function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}
function createList(arr) {
  if(arr.length == 0)
    return null;
  let head = new ListNode(arr[0], null), headNode = head;
  for(let i = 1; i < arr.length; i++) {
    let temp = new ListNode(arr[i], null);
    head.next = temp;
    head = temp;
  }
  return headNode;
}
function showList(head) {
  while(head) {
    console.log(head.val);
    head = head.next;
  }
}
/**
 * @param {number} m
 * @param {number} n
 * @param {ListNode} head
 * @return {number[][]}
 */
var spiralMatrix = function(m, n, head) {
  head = createList(head);
  let result = new Array(m);
  for(let i = 0; i < m; i++) {
    result[i] = new Array(n).fill(-1);
  }
  let directionArr = ['right', 'down', 'left', 'up'], temp = head, direction = directionArr[0];

  // 改变方向
  function changeDirection(direction, i, j) {
    switch(direction) {
      case directionArr[0]:
        if(j == n - 1 || result[i][j + 1] != -1)
          return directionArr[1];
        break;
      case directionArr[1]:
        if(i == m - 1 || result[i + 1][j] != -1)
          return directionArr[2];
        break;
      case directionArr[2]:
        if(j == 0 || result[i][j - 1] != -1)
          return directionArr[3];
        break;
      case directionArr[3]:
        if(i == 0 || result[i - 1][j] != -1)
          return directionArr[0];
        break;
    }
    return null;
  }

  for(let i = 0; i < m; i++) {
    result[i] = new Array(n).fill(-1);
  }
  let indexI = 0, indexJ = 0;
  while(temp) {
    result[indexI][indexJ] = temp.val;
    if(changeDirection(direction, indexI, indexJ)) {
      direction = changeDirection(direction, indexI, indexJ);
    }
    switch(direction) {
      case directionArr[0]:
        indexJ++;
        break;
      case directionArr[1]:
        indexI++;
        break;
      case directionArr[2]:
        indexJ--;
        break;
      case directionArr[3]:
        indexI--;
        break;
    }
    temp = temp.next;
  }
  return result;
};
let m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0];
console.log(spiralMatrix(m, n, head));
m = 1, n = 4, head = [0,1,2];
console.log(spiralMatrix(m, n, head));
